#小程序：#小程序://银愉壹品/mAwxfTIvTL9okmf
#一定要使用对应的小程序，对应的form-type
# 环境变量AUTH 不要带Bearer 多账号&
import requests
import time
import json
import os

# 1. 获取用户信息
def get_user_info(headers):
    user_info_url = "https://n03.sentezhenxuan.com/api/updateTxInfo"
    print("===== 正在获取用户信息 =====")
    try:
        response = requests.get(user_info_url, headers=headers, timeout=10)
        response.raise_for_status()
        user_data = response.json()
        if user_data.get("status") == 200 and "data" in user_data:
            nickname = user_data["data"].get("nickname", "未知用户")
            now_money = user_data["data"].get("now_money", "0.00")
            print(f"\n👤 用户信息：")
            print(f"昵称：{nickname}")
            print(f"当前余额：{now_money}元")
            return {"nickname": nickname, "now_money": now_money}
        else:
            print(f"用户信息获取失败：{user_data.get('msg', '未知错误')}")
            return {}
    except requests.exceptions.RequestException as e:
        print(f"用户信息接口请求失败：{str(e)}")
        return {}

# 2. 获取视频列表
def get_video_from_api(headers):
    list_url = "https://n03.sentezhenxuan.com/api/video/list?page=1&limit=10&status=1&source=0&isXn=1"
    print("\n===== 正在通过接口获取视频列表 =====")
    try:
        response = requests.get(list_url, headers=headers, timeout=10)
        response.raise_for_status()
        data = response.json()
        video_list = []
        if data.get("status") == 200 and "data" in data:
            total_money = 0.0
            print("\n===== 接口获取到的视频信息 =====")
            for idx, video in enumerate(data["data"], 1):
                je = video.get("je", "0.00")
                je_float = float(je) if isinstance(je, (int, float)) and je is not None else 0.0
                je = f"{je_float:.2f}" if je_float != 0 else "0.00"
                video_info = {
                    "idx": idx,
                    "id": video.get("id", "无"),
                    "video_name": video.get("video_name", "无"),
                    "wait_time": video.get("wait_time", 0),
                    "je": je,
                    "je_float": je_float
                }
                video_list.append(video_info)
                total_money += je_float
                print(f"\n视频{idx}:")
                print(f"id: {video_info['id']}")
                print(f"名称: {video_info['video_name']}")
                print(f"等待时间: {video_info['wait_time']}秒")
                print(f"金额: {video_info['je']}元")
            print(f"\n📊 视频金额累加（预览）：{total_money:.2f}元")
            return video_list
        else:
            print(f"接口返回异常：{data.get('msg', '未知错误')}")
            return []
    except requests.exceptions.RequestException as e:
        print(f"接口请求失败：{str(e)}")
        return []

# 3. 批量上报视频播放时长
def report_video_job(video_list, headers):
    if not video_list:
        print("\n⚠️ 无视频数据，跳过上报流程")
        return 0
    job_url = "https://n03.sentezhenxuan.com/api/video/videoJob"
    print("\n\n===== 开始批量上报播放时长 =====")
    success_count = 0
    for video in video_list:
        vid = video["id"]
        wait_time = video["wait_time"]
        video_name = video["video_name"]
        if vid == "无" or wait_time == 0:
            print(f"\n跳过无效视频：{video_name}（id或等待时间缺失）")
            continue
        start_time = int(time.time() * 1000)
        end_time = start_time + (wait_time * 1000)
        payload = {
            "vid": vid,
            "startTime": start_time,
            "endTime": end_time,
            "baseVersion": "3.8.12",
            "playMode": 0
        }
        try:
            response = requests.post(
                job_url, 
                data=json.dumps(payload), 
                headers=headers, 
                timeout=10
            )
            response.raise_for_status()
            print(f"\n===== 上报视频：{video_name} =====")
            print(f"vid: {vid}, 等待时间: {wait_time}秒")
            print(f"上报结果: 成功 → {response.text[:50]}...")
            success_count += 1
        except requests.exceptions.RequestException as e:
            print(f"\n❌ 视频{video_name}上报失败：{str(e)}")
        time.sleep(3)
    return success_count

# 4. 提现接口调用（保持原逻辑）
def withdraw_money(headers):
    withdraw_url = "https://n03.sentezhenxuan.com/api/userTx"
    print("\n\n===== 开始执行提现操作 =====")
    try:
        response = requests.get(withdraw_url, headers=headers, timeout=10)
        response.raise_for_status()
        withdraw_result = response.json()
        print(f"📤 提现请求已发送，结果如下：")
        print(f"状态码：{response.status_code}")
        print(f"返回信息：{withdraw_result.get('msg', '无')}")
        print(f"提现详情：{withdraw_result.get('data', '无')}")
    except requests.exceptions.RequestException as e:
        print(f"❌ 提现失败：{str(e)}")

# 5. 生成请求头
def get_common_headers(auth):
    return {
        'User-Agent': "Mozilla/5.0 (Linux; Android 14; 22041211AC Build/UP1A.231005.007; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/138.0.7204.180 Mobile Safari/537.36 XWEB/1380283 MMWEBSDK/20250201 MMWEBID/2536 MicroMessenger/8.0.60.2860(0x28003C3F) WeChat/arm64 Weixin NetType/4G Language/zh_CN ABI/arm64 MiniProgramEnv/android",
        'content-type': "application/json",
        'form-type': "routine-yipin",
        'authori-zation': f"Bearer {auth}",
        'cb-lang': "zh-CN",
        'charset': "utf-8",
        'referer': "https://servicewechat.com/wx4bd570b27d09d023/9/page-frame.html"
    }

# 单个账号流程（新增withdraw_switch参数控制提现）
def run_single_account(auth, account_idx, withdraw_switch):
    print(f"\n{'='*50}\n开始处理第{account_idx}个账号\n{'='*50}")
    headers = get_common_headers(auth)
    
    # 步骤1：获取用户信息
    user_info = get_user_info(headers)
    time.sleep(2)
    
    # 步骤2：获取视频列表
    video_info_list = get_video_from_api(headers)
    
    # 步骤3：批量上报视频
    print(f"\n✅ 共获取到{len(video_info_list)}个视频，准备上报...")
    success_report = report_video_job(video_info_list, headers)
    
    # 步骤4：根据开关控制是否提现
    print("\n\n" + "="*60)
    print(f"🎉 视频相关流程结束！")
    print(f"📊 总视频数：{len(video_info_list)}个 | 成功上报：{success_report}个")
    if user_info:
        print(f"👤 当前用户：{user_info['nickname']} | 账户余额：{user_info['now_money']}元")
    print("="*60)
    
    if withdraw_switch:
        print("\n⏳ 准备执行提现操作（3秒后开始）...")
        time.sleep(3)
        withdraw_money(headers)
    else:
        print("\n⚠️ 提现开关已关闭，跳过提现操作")
    
    print(f"\n{'='*50}\n第{account_idx}个账号处理完成\n{'='*50}")
    time.sleep(5)

# 主执行逻辑（新增提现开关配置）
if __name__ == "__main__":
    # 读取环境变量AUTH（多账号&分隔）
    auth_env = os.getenv("AUTH")
    if not auth_env:
        print("❌ 未找到环境变量AUTH，请配置后再运行！")
        exit()
    auth_list = auth_env.split("&")
    print(f"✅ 读取到{len(auth_list)}个账号的AUTH")
    
    # 自定义提现开关：True=执行提现，False=跳过提现（可直接修改此处配置）
    WITHDRAW_SWITCH = False  # 核心配置：改为False即可全局关闭提现
    
    # 循环处理每个账号（传入提现开关参数）
    for idx, auth in enumerate(auth_list, 1):
        run_single_account(auth, idx, WITHDRAW_SWITCH)
    
    print("\n📝 所有账号流程执行完毕！")